<template>
  <div class="container">
    <list-title :show-title="false" btn-text="创建里程碑" @add="handleAdd" />

    <!-- 示意图 -->
    <sketch
      :all-node-rows="allNodeRows"
      :show-node-rows="showNodeRows"
      :show-all="showAll"
      :row-size="ROW_SIZE"
      @expand="handleExpand"
    />

    <!-- 搜索区 -->
    <a-form
      :model="searchForm"
      label-align="left"
      layout="inline"
      auto-label-width
      class="search-area"
    >
      <a-form-item
        field="name"
        label="名称"
        label-col-flex="auto"
        content-class="item"
      >
        <a-input
          v-model="searchForm.name"
          placeholder="请输入"
          allow-clear
          @change="handleSearch"
        />
      </a-form-item>
      <a-form-item
        label="里程碑时间"
        label-col-flex="auto"
        content-class="range-item"
      >
        <a-range-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
      </a-form-item>
    </a-form>

    <div class="table-container">
      <a-table
        class="table"
        :loading="loading"
        :columns="teamColumns"
        :data="milestoneList"
        :scroll="{ x: '100%', y: '100%' }"
        :bordered="false"
        :pagination="pagination"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #operations="{ record }">
          <a-button type="text" size="small" @click="handleEdit(record)"
            >编辑
          </a-button>
        </template>
      </a-table>
    </div>

    <milestone-dialog
      v-model:visible="dialogVisible"
      :origin-data="milestoneInfo"
      :handle-type="handleType"
      @refresh="handleRefresh"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, reactive, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { MilestoneRecord, queryMilestoneList } from './api';
  import { ProjectRecord, queryProjectDetail } from '../project/api';
  import MilestoneDialog from './components/milestone-info.vue';
  import ListTitle from '../components/list-title.vue';
  import Sketch from './components/sketch.vue';

  // 项目信息
  const route = useRoute();
  const projectId = computed(() => {
    return String(route?.params?.projectId);
  });
  const emptyProject: ProjectRecord = {
    id: projectId.value,
    name: '',
    code: '',
    budget: '',
    type: 0,
    protemId: '',
    planStart: '',
    planEnd: '',
    description: '',
  };
  const projectInfo = ref<ProjectRecord>(emptyProject);

  // 新增/编辑弹窗
  const dialogVisible = ref(false);
  const handleType = ref('view');
  const emptyMilestone = {
    projectId: projectId.value,
    name: '',
    endTime: '',
    describe: '',
  };
  const milestoneInfo = ref<MilestoneRecord>({ ...emptyMilestone });

  // 搜索栏
  const searchForm = reactive<any>({
    name: '',
    startTime: '',
    endTime: '',
  });
  const dateRange = ref([]);

  // 列表
  const { loading, setLoading } = useLoading(true);
  const milestoneList = ref<MilestoneRecord[]>([]);
  const teamColumns = computed<TableColumnData[]>(() => [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
      width: 62,
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '计划结束时间',
      dataIndex: 'endTime',
      align: 'center',
    },
    {
      title: '交付物描述',
      dataIndex: 'describe',
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '操作',
      slotName: 'operations',
      align: 'center',
      width: 140,
    },
  ]);

  const pagination = reactive({
    showTotal: true,
    showPageSize: true,
    showJumper: true,
    pageSize: 10,
    current: 1,
    total: 0,
  });

  // 示意图
  const showAll = ref(false); // 是否展示所有节点
  const allMilestoneList = ref<MilestoneRecord[]>([]); // 所有里程碑列表
  const ROW_SIZE = 4; // 一行最多展示几个节点

  // 所有节点二维数组
  const allNodeRows = computed(() => {
    const allNodes = JSON.parse(JSON.stringify(allMilestoneList.value));
    const startNode = {
      id: 'startNode',
      name: '项目启动',
      endTime: projectInfo.value.planStart?.split(' ')[0],
    };
    const endNode = {
      id: 'endNode',
      name: '项目结束',
      endTime: projectInfo.value.planEnd?.split(' ')[0],
    };
    allNodes.unshift(startNode);
    allNodes.push(endNode);

    const rows = [];
    for (let i = 0; i < allNodes.length; i += ROW_SIZE) {
      rows.push(allNodes.slice(i, i + ROW_SIZE));
    }
    return rows;
  });

  // 当前展示节点二维数组
  const showNodeRows = computed(() => {
    if (showAll.value) {
      // 展示所有节点
      return allNodeRows.value;
    }
    // 展示一行节点
    return allNodeRows.value.slice(0, 1);
  });

  // 查询项目详细信息
  const getProjectDetail = () => {
    const params = {
      id: projectId.value,
    };
    queryProjectDetail(params)
      .then((res) => {
        projectInfo.value = res.data;
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err);
      });
  };

  // 分页查询里程碑列表
  const getMilestoneList = () => {
    setLoading(true);
    const params: any = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      projectId: projectId.value,
    };
    Object.keys(searchForm).forEach((key) => {
      if (searchForm[key]) {
        params[key] = searchForm[key];
      }
    });
    queryMilestoneList(params)
      .then((res) => {
        milestoneList.value = res.data.list || [];
        pagination.total = res.data.total || 10;
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 查询所有里程碑列表
  const getAllMilestoneList = () => {
    const params = {
      pageNo: 1,
      pageSize: 1000,
      projectId: projectId.value,
    };
    queryMilestoneList(params)
      .then((res) => {
        allMilestoneList.value = res.data.list || [];
      })
      .catch((err) => {
        // eslint-disable-next-line no-console
        console.log(err);
      });
  };

  // 示意图展开/折叠
  const handleExpand = () => {
    showAll.value = !showAll.value;
  };

  const handleSearch = () => {
    pagination.current = 1;
    getMilestoneList();
  };

  // 新增/编辑后刷新页面
  const handleRefresh = () => {
    handleSearch();
    getAllMilestoneList();
  };

  // 搜索栏时间范围变化事件
  const handleDateChange = (time: any) => {
    if (time && time.length === 2) {
      [searchForm.startTime, searchForm.endTime] = time;
    } else {
      searchForm.startTime = '';
      searchForm.endTime = '';
    }
    handleSearch();
  };

  // 创建里程碑
  const handleAdd = () => {
    handleType.value = 'add';
    milestoneInfo.value = { ...emptyMilestone };
    dialogVisible.value = true;
  };

  // 编辑里程碑
  const handleEdit = (record: MilestoneRecord) => {
    handleType.value = 'edit';
    milestoneInfo.value = {
      ...record,
    };
    dialogVisible.value = true;
  };

  // 页码改变事件处理
  const handlePageChange = (page: number) => {
    pagination.current = page;
    getMilestoneList();
  };

  // 每页条数改变事件处理
  const handlePageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    getMilestoneList();
  };

  getProjectDetail();
  getMilestoneList();
  getAllMilestoneList();
</script>

<style scoped lang="less">
  .search-area {
    padding: 24px 0;

    :deep(.item) {
      width: 220px;
    }

    :deep(.range-item) {
      width: 240px;
    }
  }

  .container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 156px);

    .table-container {
      flex: 1;
      overflow: hidden;
    }
  }

  /* 修复table高度变化后，出现两个滚动条的问题 */
  :deep(.arco-table-container > .arco-scrollbar > .arco-scrollbar-track) {
    display: none;
  }
</style>
